import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { getToken, refreshAccessToken, removeToken } from '@/utils/token'
import { Router } from 'vue-router'
import { NOT_FOUND_ROUTE_404 } from '../routes/basicRoutes'

const WHITE_LIST = ['/login', '/redirect']
export function createPermissionGuard(router: Router) {
  const userStore: any = useUserStore()
  const permissionStore = usePermissionStore()
  router.beforeEach(async (to: { path: string; query: any }, from: any, next: any) => {
    const token = getToken()
    
    if (token) {
      if (to.path === '/login') {
        next()
      } else {
        if (userStore.userId) {
          // 重新保存token
          refreshAccessToken()
          next()
        } else {
          try {
            await userStore.GetUserInfo()
            const accessRoutes = permissionStore.generateRoutes(userStore.role)
            accessRoutes.forEach((route: any) => {
              !router.hasRoute(route.name) && router.addRoute(route)
            })
            router.addRoute(NOT_FOUND_ROUTE_404)
            next({ ...to, replace: true }) // 这里相当于push到一个页面 不在进入路由拦截
          } catch (error) {
            console.log(error)
            removeToken()
            next({ path: '/login', query: { ...to.query, redirect: to.path } })
          }
        }
      }
    } else {
      if (WHITE_LIST.includes(to.path)) {
        next()
      } else {
        next({ path: '/login', query: { ...to.query, redirect: to.path } })
      }
    }
  })
}
function NOT_FOUND_ROUTE(NOT_FOUND_ROUTE: any) {
  throw new Error('Function not implemented.')
}

